package com.fuershiye.woman.monitor.export;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;

/**
 * POI动态导出EXCEL文档
 */
public class ExportExcel<T> {
	
	private final static String title = "上报数据";
	private final static String pattern = "yyyy-MM-dd";
	
	/**
	 * 
	 * @param headers
	 *            表格属性列名数组
	 * @param dataset
	 *            需要显示的数据集合
	 */
	@SuppressWarnings("deprecation")
	public boolean exportExcel(String[] headers, List<Map<String, Object>> dataset, String path) {
		
		// 声明一个工作薄
		HSSFWorkbook workbook = new HSSFWorkbook();
		// 生成一个表格
		HSSFSheet sheet = workbook.createSheet(title);
		
//		// 设置表格默认列宽度为15个字节
		sheet.setDefaultColumnWidth((short) 24);
		
		HSSFCellStyle styleBody = mkBodyStyle(workbook);
		HSSFCellStyle styleHeader = mkHeaderStyle(workbook);
		
		HSSFRow row = addHeader(sheet, styleHeader, headers);
		workbook = addBody(workbook, sheet, styleBody, row, dataset);

		OutputStream out = null;
		try {
			out = new FileOutputStream(path);
			workbook.write(out);
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(out!=null){
				try {
					out.close();
				}catch (Exception e){
					e.printStackTrace();
				}
			}
		}

		return false;
	}
	
	// 生成Header样式
	private HSSFCellStyle mkHeaderStyle(HSSFWorkbook workbook){
		HSSFCellStyle style = workbook.createCellStyle();
		// 设置这些样式
		style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
		style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		// 生成一个字体
		HSSFFont font = workbook.createFont();
		font.setColor(HSSFColor.VIOLET.index);
		font.setFontHeightInPoints((short) 12);
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		// 把字体应用到当前的样式
		style.setFont(font);
		return style;
	}

	// 生成body样式
	private HSSFCellStyle mkBodyStyle(HSSFWorkbook workbook){
		HSSFCellStyle style = workbook.createCellStyle();
		style.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
		style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
		// 生成另一个字体
		HSSFFont font = workbook.createFont();
		font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
		// 把字体应用到当前的样式
		style.setFont(font);
		
		return style;
	}

	// 表格标题行
	@SuppressWarnings("deprecation")
	private HSSFRow addHeader(HSSFSheet sheet, HSSFCellStyle style, String[] headers){
		
		HSSFRow row = sheet.createRow(0);
		for (short i = 0; i < headers.length; i++) {
			HSSFCell cell = row.createCell(i);
			cell.setCellStyle(style);
			HSSFRichTextString text = new HSSFRichTextString(headers[i]);
			cell.setCellValue(text);
//			cell.setCellValue(headers[i]);
		}
		return row;
	}
	
	@SuppressWarnings("rawtypes")
	private HSSFWorkbook addBody(HSSFWorkbook workbook, HSSFSheet sheet, HSSFCellStyle style, HSSFRow row, List<Map<String, Object>> listData){

		int index = 0;
		for (Map<String, Object> data : listData) {
			index++;
			row = sheet.createRow(index);

			int i = 0;
			Iterator<Entry<String, Object>> map=data.entrySet().iterator();
			while(map.hasNext()){//只遍历一次,速度快

				Map.Entry e=(Map.Entry)map.next();
				HSSFCell cell = row.createCell(i);
//				cell.setCellStyle(style);
				cell = getText(cell, e.getValue());
				i++;
			}
		}
		return workbook;
	}
	
	private HSSFCell getText(HSSFCell cell, Object value){

		// 判断值的类型后进行强制类型转换
		String textValue = null;
		if (value instanceof Date) {
			Date date = (Date) value;
			SimpleDateFormat sdf = new SimpleDateFormat(pattern);
			textValue = sdf.format(date);
		} else if(value!=null){
			// 其它数据类型都当作字符串简单处理
			textValue = value.toString();
		}
		
		// 如果不是图片数据，就利用正则表达式判断textValue是否全部由数字组成
		if (textValue != null) {
			Pattern p = Pattern.compile("^//d+(//.//d+)?$");
			Matcher matcher = p.matcher(textValue);
			if (matcher.matches()) {
				// 是数字当作double处理
				cell.setCellValue(Double.parseDouble(textValue));
			} else {
//				cell.setCellType(HSSFCell.CELL_TYPE_STRING);
//				cell.setCellValue(textValue);
				cell.setCellValue(new HSSFRichTextString(textValue));
			}
		}
		return cell;
	}
	
}